from sqlmodel import Session, create_engine, select, SQLModel

from common.config import settings
from app.users.models import User
from app.users.models_help import create_user
from app.users.permission_help import (
    init_default_permissions, 
    init_default_roles, 
    assign_default_permissions_to_roles
)

engine = create_engine(settings.SQLALCHEMY_DATABASE_URI)


def init_db(session: Session) -> None:
    # Tables should be created with Alembic migrations
    # But if you don't want to use migrations, create
    # the tables un-commenting the next lines
    # from sqlmodel import SQLModel

    SQLModel.metadata.create_all(engine)
    
    # 初始化权限系统
    init_default_permissions(session)
    init_default_roles(session)
    assign_default_permissions_to_roles(session)
    
    # 创建超级管理员用户
    select_user = select(User).where(User.email == settings.SUPERUSER_EMAIL)
    user = session.exec(select_user).first()
    if not user:
        name = settings.SUPERUSER_NAME
        password = settings.SUPERUSER_PASSWORD
        email = settings.SUPERUSER_EMAIL
        user = create_user(session=session, name=name, password=password, email=email, is_active=True)



